package org.example.test.controller;

import org.example.test.model.OrderItemModel;
import org.example.test.model.OrdersModel;
import org.example.test.response.CommonResponse;
import org.example.test.response.ResponseBuilder;
import org.example.test.service.OrdersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrdersService orderService;  // 订单服务层接口

    /**
     * 创建新订单
     * @param orderRequest 订单请求数据（包含用户ID、商品列表、总价等）
     * @return 创建成功的订单详情（含订单ID）
     */
    @PostMapping("/create")
    public CommonResponse createOrder(@RequestBody OrdersModel orderRequest) {
        try {
            LOGGER.info("Create order request: {}", orderRequest);
            OrdersModel order = orderService.createOrder(orderRequest);  // 调用服务层创建订单
            return ResponseBuilder.success(order);  // 返回完整订单数据
        } catch (Exception e) {
            LOGGER.error("Error creating order", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 更新订单信息（非状态字段）
     * @param orderId 订单ID
     * @param orderRequest 更新后的订单数据
     * @return 空响应（仅表示操作状态）
     */
    @PutMapping("/update")
    public CommonResponse updateOrder(@RequestParam Long orderId, @RequestBody OrdersModel orderRequest) {
        try {
            LOGGER.info("Update order request - orderId: {}", orderId);
            orderService.updateOrder(orderId, orderRequest);  // 更新订单基础信息
            return ResponseBuilder.success();
        } catch (Exception e) {
            LOGGER.error("Error updating order", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 更新订单状态（如PAID/SHIPPED等）
     * @param orderId 订单ID
     * @param status 新状态值
     * @return 空响应
     */
    @PutMapping("/updateStatus")
    public CommonResponse updateStatus(@RequestParam Long orderId, @RequestParam String status) {
        try {
            LOGGER.info("Update order request - orderId: {}, new status: {}", orderId, status);
            orderService.updateOrderStatus(orderId, status);  // 专门处理状态变更
            return ResponseBuilder.success();
        } catch (Exception e) {
            LOGGER.error("Error updating order", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 删除订单（逻辑删除或物理删除）
     * @param orderId 订单ID
     * @return 空响应
     */
    @DeleteMapping("/delete")
    public CommonResponse deleteOrder(@RequestParam Long orderId) {
        try {
            LOGGER.info("Delete order request - orderId: {}", orderId);
            orderService.deleteOrder(orderId);  // 执行删除操作
            return ResponseBuilder.success();
        } catch (Exception e) {
            LOGGER.error("Error deleting order", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 查询单个订单详情
     * @param orderId 订单ID
     * @return 订单完整数据（含订单项）
     */
    @GetMapping("/get")
    public CommonResponse getOrder(@RequestParam Long orderId) {
        try {
            LOGGER.info("Get order request - orderId: {}", orderId);
            OrdersModel order = orderService.getOrderById(orderId);  // 获取订单主表和关联项
            return ResponseBuilder.success(order);
        } catch (Exception e) {
            LOGGER.error("Error getting order", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 查询用户的所有订单
     * @param userId 用户ID
     * @return 订单列表（简略信息）
     */
    @GetMapping("/listByUser")
    public CommonResponse listOrdersByUser(@RequestParam("userId") Long userId) {
        try {
            LOGGER.info("List orders by user request - userId: {}", userId);
            List<OrdersModel> orders = orderService.listOrdersByUser(userId);  // 获取用户历史订单
            return ResponseBuilder.success(orders);
        } catch (Exception e) {
            LOGGER.error("Error listing orders", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 商家查询商品关联订单（用于查看销售情况）
     * @param productId 商品ID
     * @return 包含该商品的订单项列表
     */
    @GetMapping("/getMerchantOrder")
    public CommonResponse getMerchantOrder(@RequestParam("productId") Long productId) {
        try {
            LOGGER.info("List orders by user request - productId: {}", productId);
            List<OrderItemModel> orderItemModels = orderService.getMerchantOrder(productId);  // 获取商品销售记录
            return ResponseBuilder.success(orderItemModels);
        } catch (Exception e) {
            LOGGER.error("Error listing orders", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }
}
